package Slice

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Number"
	"reflect"
)

func Has(list interface{}, value interface{}) bool {
	index := Find(list, value)
	result := int64(index) >= int64(0)
	return result
}

// Find 找到某个元素的下标
func Find(list interface{}, value interface{}) int {
	if reflect.TypeOf(list).Kind() != reflect.Slice {
		return -1
	}

	v := reflect.ValueOf(list)
	for index := 0; index < v.Len(); index++ {
		if v.Index(index).Interface() == value {
			return index
		}
	}
	return -1
}

// Interfaces 复制一个副本
func Interfaces(list interface{}) []interface{} {
	if reflect.TypeOf(list).Kind() != reflect.Slice {
		return make([]interface{}, 0)
	}
	v := reflect.ValueOf(list)

	result := make([]interface{}, 0)

	for index := 0; index < v.Len(); index++ {
		result = append(result, v.Index(index).Interface())
	}

	return result
}

// Reverse 将数组反转
func Reverse(array interface{}) {
	list := reflect.ValueOf(array)

	for i, j := 0, list.Len()-1; i < j; i, j = i+1, j-1 {
		tmp := list.Index(i).Interface()
		list.Index(i).Set(list.Index(j))
		list.Index(j).Set(reflect.ValueOf(tmp))
	}
}

func Append[T any](list []T, tail []T) []T {
	for _, v := range tail {
		list = append(list, v)
	}

	return list
}

func Split[T any](dataList []T, pageSize int) [][]T {
	resultList := make([][]T, 0)

	page := make([]T, 0)
	for _, data := range dataList {
		if len(page) < pageSize {
			page = append(page, data)
		} else {
			resultList = append(resultList, page)
			page = make([]T, 0)
		}
	}

	if len(page) != 0 {
		resultList = append(resultList, page)
	}

	return resultList
}

// Remove 删除某个元素
func Remove(slicePtr interface{}, index int) {
	// 获取slice的反射对象
	slice := reflect.ValueOf(slicePtr)
	if slice.Kind() != reflect.Ptr || slice.Elem().Kind() != reflect.Slice {
		return
	}

	// 获取slice指向的数组的反射对象
	slice = slice.Elem()

	// 删除元素
	slice.Set(reflect.AppendSlice(slice.Slice(0, index), slice.Slice(index+1, slice.Len())))
}

// ToMapList 转换为MapList格式
func ToMapList(list []interface{}) []map[string]interface{} {
	result := make([]map[string]interface{}, 0)

	for _, val := range list {
		data := val.(map[string]interface{})
		result = append(result, data)
	}

	return result
}

// ToInt64List 转换为MapList格式
func ToInt64List(list []interface{}) []int64 {
	result := make([]int64, 0)

	for _, val := range list {
		data := Number.MakeInt64(val)
		result = append(result, data)
	}

	return result
}

// ToList
// 将[]interface{}强制转换为具体的类型，valueType是给出类型的样例
func ToList[V any](list []interface{}, defaultValue V) []V{
	outList := make([]V,0)
	for _, data := range list {
		if data == nil {
			data = defaultValue
		}

		outList = append(outList, data.(V))
	}

	return outList
}
